#include "setwig.h"
#include "ui_setwig.h"


// 设置服务器地址和端口0
QHostAddress serverAddress("192.168.50.133"); // 服务器IP地址
quint16 serverPort = 7788;// 服务器端口号

SetWig::SetWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SetWig)
{
    ui->setupUi(this);
//    socket = new QUdpSocket(this);

    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::Any, serverPort);
    socket->setReadBufferSize(655360); //
    // 创建定时器对象

    timer_stream = new QTimer(this);
    // 设置触发时间
    timer_stream->setInterval(50);
//    timer_stream->setInterval(true);
    connect(timer_stream,SIGNAL(timeout()),
            this,SLOT(timeoutStreamSlot()));
    connect(ui->pushButton,SIGNAL(clicked()),
            this,SLOT(sendSlot()));
    connect(socket,SIGNAL(readyRead()),
            this,SLOT(getStreamSlot()));
    connect(ui->pushButton_2,SIGNAL(clicked()),
            this,SLOT(getPhotoSlot()));
}

SetWig::~SetWig()
{
    delete ui;
}

void SetWig::paintEvent(QPaintEvent *event)
{
    //
    QPainter painter(this);
    QPixmap map(":/new/prefix1/01.png");
    // 绘制图片
    // 参数1、2 横轴及纵轴坐标
    // 参数3、4 绘制的宽高
    // 参数5    绘制的内容
    painter.drawPixmap(0,0,width(),height(),map);
}

void SetWig::sendSlot()
{
    ui->pushButton_2->setEnabled(true);
    socket->connectToHost(serverAddress,serverPort);
    // 发送的数据
    QByteArray datagram = "get_stream";
    // 发送数据
    socket->writeDatagram(datagram, serverAddress, serverPort);
    timer_stream->start();

}

void SetWig::getStreamSlot()
{
    while (socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        QString message = QString::fromUtf8(datagram);
        datagram.resize(socket->pendingDatagramSize());
        socket->read(datagram.data(), datagram.size());
        // 处理数据

        QString data = datagram;
        QImage image;//保存用这个数据
        if (image.loadFromData(datagram))
        {
            QPixmap pixmap = QPixmap::fromImage(image);
            ui->label->setPixmap(pixmap);
            ui->label->setScaledContents(true);
        }
    }
}

void SetWig::timeoutStreamSlot()
{
   QByteArray datagram = "get_stream";
    //sendSlot();
    socket->writeDatagram(datagram, serverAddress, serverPort);
    getStreamSlot();
}



void SetWig::getPhotoSlot()
{
    lable = ui->label;
    QPixmap pixmap =*lable->pixmap(); // 获取 QLabel 中的 QPixmap

    // 如果 QPixmap 存在，保存为文件
    if (!pixmap.isNull()) {
        // 弹出文件保存对话框，让用户选择保存路径和文件名
        QString filePath = QFileDialog::getSaveFileName(this, tr("Save Image"), QDir::homePath(), tr("Images (*.png *.jpg)"));

        if (!filePath.isEmpty()) {
            if (pixmap.save(filePath)) {
                qDebug() << "Image saved successfully to:" << filePath;
            } else {
                qDebug() << "Failed to save image.";
            }
        }
    } else {
        qDebug() << "No pixmap found in the label.";
    }
}
